﻿using Core.Utility.Helper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Utility.Extendsions.Json
{
    /// <summary>
    /// Unix时间戳转DateTime(单向转换)
    /// </summary>
    public class UnixTimestampToDateTimeJsonConverter : JsonConverter
    {
        /// <summary>
        /// 读取Json
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object? ReadJson(
            JsonReader reader,
            Type objectType,
            object? existingValue,
            JsonSerializer serializer)
        {
            long ts = serializer.Deserialize<long>(reader);

            return DateTimeHelper.ToDateTime(ts);
        }

        /// <summary>
        /// 能否转换
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public override bool CanConvert(Type type)
        {
            return typeof(DateTime).IsAssignableFrom(type);
        }

        /// <summary>
        /// 输出Json
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        public override void WriteJson(
            JsonWriter writer,
            object? value,
            JsonSerializer serializer)
        {
            //if (value is DateTime dateTime)
            //{
            //    writer.WriteValue(dateTime);
            //}
            writer.WriteValue(value);
        }

        /// <summary>
        /// 能否读取
        /// </summary>
        public override bool CanRead
        {
            get { return true; }
        }
    }
}
